package com.camartsApp.controller;

import com.camartsApp.Util.AliyunOssUtil;
import com.camartsApp.Util.JwtUtils;
import com.camartsApp.Util.Response;
import com.camartsApp.common.ResultVO;
import com.camartsApp.dto.PhotoFootprintDTO;
import com.camartsApp.dto.PhotoInfoDTO;
import com.camartsApp.entity.Photo;
import com.camartsApp.entity.Post;
import com.camartsApp.service.IPhotoService;
import com.camartsApp.service.PhotoService;
import com.camartsApp.service.PhotoUploadService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.time.ZoneId;

@RestController
@RequestMapping("/api/photo")
public class PhotoController {
    @Autowired
    private IPhotoService iphotoService;

    @Autowired
    private PhotoService photoService;


    @Autowired
    private AliyunOssUtil aliyunOssUtil;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private MongoTemplate mongoTemplate;

    @PostMapping("/upload")
    public ResultVO upload(@RequestParam("file") MultipartFile file,
                           @RequestParam(required = false) String aperture,
                           @RequestParam(required = false) String shutter,
                           @RequestParam(required = false) Integer iso,
                           @RequestParam(required = false) String focalLength,
                           @RequestParam(required = false) String device,
                           @RequestParam(required = false) String category,
                           @RequestParam(required = false) String takenAt,  // ISO-8601 格式，如 2025-06-14T12:00:00
                           @RequestParam(required = false) Double latitude,
                           @RequestParam(required = false) Double longitude,
                           @RequestParam(required = false) String title,
                           @RequestParam(required = false) String content,
                           HttpServletRequest request) {
        try {
            String token = extractToken(request.getHeader("Authorization"));
            Long userId = jwtUtils.getUserIdFromToken(token);

            if (userId == null) {
                return Response.FailResultByMsg("用户未登录或登录已过期");
            }

            // 上传文件到阿里云 OSS
            String url = aliyunOssUtil.upload(file);
            if (url == null) {
                return Response.FailResultByMsg("文件上传失败");
            }

            LocalDateTime takenDateTime = null;
            if (takenAt != null && !takenAt.isBlank()) {
                takenDateTime = LocalDateTime.parse(takenAt, java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }

            Photo photo = new Photo();
            photo.setUserId(userId);
            photo.setUrl(url);
            photo.setAperture(aperture);
            photo.setShutter(shutter);
            photo.setIso(iso);
            photo.setFocalLength(focalLength);
            photo.setDevice(device);
            photo.setCategory(category);
            photo.setLatitude(latitude != null ? new java.math.BigDecimal(latitude) : null);
            photo.setLongitude(longitude != null ? new java.math.BigDecimal(longitude) : null);
            photo.setTakenAt(takenDateTime);
            photo.setUploadedAt(LocalDateTime.now());
            photo.setStatus(1); // 默认审核中
            photo.setIsHidden(false); // 默认公开
            photo.setLikeCount(0); // 设置默认点赞量为0

            iphotoService.save(photo);

            // 创建并插入 Post 文档到 MongoDB
            if (title != null && !title.isBlank()) {
                Post post = new Post();
                post.setTitle(title);
                post.setContent(content != null ? content : "");
                post.setImageId(photo.getId().intValue());
                post.setCreateTime(new Date());
                post.setUpdateTime(new Date());
                post.setStatus(1);
                post.setLikeCount(0);
                post.setFavoriteCount(0);
                post.setIsDelete(false);

                mongoTemplate.save(post);
            } else {
                return Response.FailResultByMsg("标题不能为空");
            }

            return Response.OkByMsg("上传成功");

        } catch (Exception e) {
            e.printStackTrace();
            return Response.FailResultByMsg("上传失败：" + e.getMessage());
        }
    }

    private String extractToken(String authHeader) {
        if (authHeader == null) return null;
        return authHeader.startsWith("Bearer ") ? authHeader.substring(7) : authHeader;
    }


    /**
     * 获取用户照片足迹
     * @param userId 用户ID
     * @return 照片足迹列表
     */
    @GetMapping("/footprints/{userId}")
    public ResultVO getUserPhotoFootprints(@PathVariable String userId) {
        List<PhotoFootprintDTO> footprints = iphotoService.getUserPhotoFootprints(userId);
        if (footprints == null || footprints.isEmpty()) {
            // 根据需求，如果用户ID不存在或没有照片，可以返回404 Not Found
            return Response.FailResultByMsg("404");
        }
        return Response.OkByData(footprints);
    }

    /**
     * 根据地理位置范围查询照片
     * @param userId 用户的ID
     * @param minLat 最小纬度
     * @param minLng 最小经度
     * @param maxLat 最大纬度
     * @param maxLng 最大经度
     * @return 照片信息列表
     */
    @GetMapping("/by-location")
    public ResultVO getPhotosByLocation(
            @RequestParam String userId,
            @RequestParam Double minLat,
            @RequestParam Double minLng,
            @RequestParam Double maxLat,
            @RequestParam Double maxLng) {

        // 可选：添加参数校验逻辑
        if (minLat == null || minLng == null || maxLat == null || maxLng == null) {
            return Response.FailResultByMsg("400");
        }
        if (minLat > maxLat || minLng > maxLng) {
            return Response.FailResultByMsg("400");
        }

        List<PhotoInfoDTO> photos = iphotoService.getPhotosByLocation(userId, minLat, minLng, maxLat, maxLng);
        return Response.OkByData(photos);
    }
}